/**
 * 角色表
 * 支持定义不同的角色，一个角色可以有不同权限
 */
import { Op } from 'sequelize';

const adminRole = (sequelize, DataTypes) => {
  const AdminRole = sequelize.define(
    'adminRole',
    {
      name: {
        type: DataTypes.STRING(20),
        unique: false,
        allowNull: false,
        validate: {
          notEmpty: { args: true, msg: '角色名称必填' },
          len: { args: [2, 20], msg: '角色名称需要在2到20位之间' }
        }
      },
      description: {
        type: DataTypes.STRING,
        unique: false,
        allowNull: true
      },
      sign: {
        type: DataTypes.STRING(10),
        unique: false,
        allowNull: false
      },
      permissions: {
        type: DataTypes.ARRAY({
          type: DataTypes.SMALLINT,
          references: {
            model: sequelize.models.AdminPermission,
            key: 'id'
          },
          allowNull: false
        }),
        allowNull: true
      }
    },
    {
      freezeTableName: true, // 自定义表名
      tableName: 'admin_role',
      timestamps: true, // 是否需要增加createdAt、updatedAt、deletedAt字段
      underscored: true // 字段使用下划线，而不是驼峰式命名
      // 'paranoid': true // 设置paranoid为true（此种模式下，删除数据时不会进行物理删除，而是设置deletedAt为当前时间
    }
  );

  /**
   * 获取角色权限列表
   * @param {Number} id 角色id
   */
  AdminRole.getPermissions = async function (id) {
    const result: any[] = [];
    const thisRole = await AdminRole.findByPk(id);
    if (thisRole) {
      const permissions = await this.sequelize.models.adminPermission.findAll({
        where: {
          id: {
            [Op.in]: thisRole.permissions
          }
        },
        include: [
          {
            model: this.sequelize.models.adminPermissionClassify,
            attributes: ['id', 'name'],
            as: 'classify'
          }
        ]
      });
      if (permissions && permissions instanceof Array) {
        permissions.forEach(item => {
          if (item && item.id) {
            result.push({
              id: item.id,
              name: item.name,
              interface: item.interface,
              classify: item.classify ? item.classify.name : '',
              description: item.description
            });
          }
        });
      }
    }
    return result;
  };

  /**
   * 角色名称查重
   * @param {String} filed 需要被验证的字段
   * @param {String} value 需要被验证的字段的值
   * @param {*} self 去否忽略自己开始验证
   */
  AdminRole.isRepeat = async (filed, value, self) => {
    const query = {};
    query[filed] = value;
    if (self) {
      const roles = await sequelize.query(`SELECT COUNT(*) FROM admin_role WHERE ${filed}='${value}'`, { type: sequelize.QueryTypes.SELECT });
      return roles.some(item => parseInt(item.count) >= 2);
    } else {
      const roles = await sequelize.query(`SELECT COUNT(*) FROM admin_role WHERE ${filed}='${value}'`, { type: sequelize.QueryTypes.SELECT });
      return roles.some(item => parseInt(item.count) >= 1);
    }
  };

  return AdminRole;
};

export default adminRole;
